package studio.raptor.databus.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import studio.raptor.databus.command.Event;

import javax.jms.*;
import java.util.List;

/**
 * 队列消息生产者，每个生产者只能发送消息到一个指定的主题
 */
public final class DatabusProducer {

    private Connection connection;
    private Session session;
    private MessageProducer messageProducer;
    private static Logger log = LoggerFactory.getLogger(DatabusProducer.class);

    /**
     * 构造方法,对包内其他类开放
     */
    DatabusProducer() {}

    /**
     * 批量发送消息事件
     *
     * @param eventList 事件列表
     * @throws JMSException
     */
    public void send(List<Event> eventList) throws JMSException {
        if (eventList == null) {
            return;
        }
        for (int i = 0; i < eventList.size(); i++) {
            ObjectMessage objectMessage = session.createObjectMessage(eventList.get(i));
            this.messageProducer.send(objectMessage);
        }
        this.session.commit();
    }

    /**
     * 发送消息事件
     *
     * @param event 事件
     * @throws JMSException
     */
    public void send(Event event) throws JMSException {
        if (event == null) {
            return;
        }
        ObjectMessage objectMessage = session.createObjectMessage(event);
        this.messageProducer.send(objectMessage);
        this.session.commit();
    }

    /**
     * 关闭生产者，关闭后不可再用此生产者发送消息
     */
    public void close() {
        try {
            if (this.messageProducer != null) {
                this.messageProducer.close();
            }
            if (this.session != null) {
                this.session.close();
            }
            if (this.connection != null) {
                this.connection.close();
            }
        } catch (JMSException e) {
            log.error(e.getMessage(),e);
        }
    }

    Connection getConnection() {
        return connection;
    }

    void setConnection(Connection connection) {
        this.connection = connection;
    }

    Session getSession() {
        return session;
    }

    void setSession(Session session) {
        this.session = session;
    }

    MessageProducer getMessageProducer() {
        return messageProducer;
    }

    void setMessageProducer(MessageProducer messageProducer) {
        this.messageProducer = messageProducer;
    }
}
